<template>
	<view class="page">
		<cl-message ref="message"></cl-message>
		<cl-confirm ref="confirm"></cl-confirm>
		<!-- 拍品图片轮播图 -->
		<swiper indicator-dots="true" indicator-active-color="white" autoplay="true">
			<swiper-item v-for="(image, index) in lotInfo.images" :key="index">
				<view class="swiper-content-wrapper">
					<image class="swiper-image" mode="aspectFit" :src="image"></image>
				</view>
			</swiper-item>
		</swiper>
		<view class="countdown" :style="lotInfo.tag == 1 ? '' : 'background-color: #787B84;'">
			<image v-if="lotInfo.tag == 1" src="/static/icon/countdown.png"></image>
			<view v-else class="icon iconfont icon-paimai u-f-ajc" style="color: #FFFFFF; font-size: 18px;"></view>
			<text>{{lotInfo.tag == 0 ? "已结束 · 拍品已成交" : lotInfo.tag == 1 ? "正在拍卖" : "已流拍"}}</text>
			<cl-countdown v-if="lotInfo.tag == 1" :datetime="lotInfo.endDate" :layout="layout" :splitor="splitor" @change="countdownChange"
			 style="margin-left: 30rpx;"></cl-countdown>
		</view>
		<view class="content-wrapper">
			<!-- 拍品信息 -->
			<text class="lot-title">{{lotInfo.title}}</text>
			<view class="price-wrapper">
				<view class="text-wrapper">
					<view class="rmb">RMB</view>
					<view class="price-text" :style="lotInfo.tag == 1 ? '' : 'color: #9F9F9F;'">{{lotInfo.tag != 0 ? "当前价" : "落槌价"}}</view>
				</view>
				<view class="price" :style="lotInfo.tag == 1 ? '' : 'color: #9E9E9E;'">{{int2str(lotInfo.tag != 0 ? (lotInfo.lotRecordList.length == 0 ? lotInfo.startPrice : lotInfo.lotRecordList[0].price) : lotInfo.lotRecordList[0].price)}}</view>
			</view>
			<!-- 拍卖浏览收藏 -->
			<view class="lot-info-wrapper">
				<view class="lot-info-block" style="border-right: 1rpx solid #D9D9D9;">
					<text style="color: #9F9F9F;">浏览</text>
					<text style="margin: 0 10rpx;">{{lotInfo.look}}</text>
					<text style="color: #9F9F9F;">次</text>
				</view>
				<view class="lot-info-block">
					<text style="color: #9F9F9F;">收藏</text>
					<text style="margin: 0 10rpx;">{{lotInfo.collectionNum}}</text>
					<text style="color: #9F9F9F;">次</text>
				</view>
			</view>
		</view>
		<!-- 拍卖记录 -->
		<view class="lot-record-wrapper" v-if="lotInfo.lotRecordList.length > 0">
			<view class="lot-record-head" @click="gotoRecord(lotInfo.lotId)">
				<view class="lot-record-head-left">
					<view class="icon material-icons icon-paimaijilu u-f-ajc lot-record-head-arrow"></view>
					<text>拍卖记录</text>
				</view>
				<view class="lot-record-head-right">
					<text>{{lotInfo.collectionNum}}条</text>
					<view class="icon iconfont icon-keyboard_arrow_right u-f-ajc lot-record-head-arrow"></view>
				</view>
			</view>
			<view class="lot-record-list">
				<view v-for="(item, index) in lotInfo.lotRecordList" :key="index" class="lot-record-list-block" :style="index == 0 ? 'color: #FE6A00;' : index == 1 ? 'color: #666666;' : 'color: #9A9A9A' ">
					<view class="lot-record-list-info">
						<text class="lot-record-list-uid">{{item.uid}}</text>
						<text class="lot-record-list-type">{{index == 0 ? (lotInfo.tag == 0 ? "拍得" : "领先") : "出局"}}</text>
						<text class="lot-record-list-time">{{formatRecordTime(item.date)}}</text>
					</view>
					<text class="lot-record-list-price">￥{{int2str(item.price)}}</text>
				</view>
			</view>
		</view>
		<view class="lot-type-wrapper">
			<view class="lot-type-block">
				<text class="lot-type-text" style="margin-right: 32rpx;">起拍价</text>
				<text class="lot-type-info">￥{{int2str(lotInfo.startPrice)}}</text>
			</view>
			<view class="lot-type-block">
				<text class="lot-type-text" style="margin-right: 6rpx;">加价幅度</text>
				<text class="lot-type-info">￥{{int2str(lotInfo.markupRange)}}</text>
			</view>
			<view class="lot-type-block">
				<text class="lot-type-text">开拍时间</text>
				<text class="lot-type-info">{{getCNDate(lotInfo.date)}}</text>
			</view>
			<view class="lot-type-block">
				<text class="lot-type-text">结束时间</text>
				<text class="lot-type-info">{{getCNDate(lotInfo.endDate)}}</text>
			</view>
			<view class="lot-type-block">
				<text class="lot-type-text">拍品类型</text>
				<text class="lot-type-info">{{getCNType(lotInfo.type)}}</text>
			</view>
		</view>
		<view class="gray-background">
			<view class="user-wrapper">
				<text class="user-text">拍卖人</text>
				<view class="user-info" @tap="gotoUserInfo(lotInfo.uid)">
					<view class="left-wrapper">
						<image class="user-headImg" :src="lotInfo.photo"></image>
						<text class="user-name">{{lotInfo.name}}</text>
					</view>
					<view class="icon iconfont icon-keyboard_arrow_right u-f-ajc"></view>
				</view>
			</view>
			<view class="lot-detail-wrapper">
				<text class="lot-detail-title">拍品详情</text>
				<text decode="true" class="lot-detail-info">{{lotInfo.info}}</text>
			</view>
			<view style="height: 110rpx;"></view>
			<view class="foot-wrapper">
				<view class="collection-wrapper" @tap="collect">
					<view class="icon iconfont icon-shoucang u-f-ajc" :style="isCollection ? 'color: #FE6A00;' : '' "></view>
					<text>{{isCollection ? "已收藏" : "收藏"}}</text>
				</view>
				<view v-if="lotInfo.tag == 1" class="btn" @tap="click">立即参拍</view>
				<view v-else class="btn" style="background-color: #9C9C9C;">立即参拍</view>
			</view>
		</view>
		<cl-dialog
			:visible.sync="dialog"
			:show-cancel-button="false"
			:show-confirm-button="false"
		>
			<view class="cs-det">
				<input type="text" password placeholder="请输入支付密码" maxlength="6" v-model="payPassword" />
			</view>
			<template slot="footer">
				<cl-button size="small" @tap="closeDialog">
					<text>取消</text>
				</cl-button>
				<cl-button type="primary" size="small" @tap="checkPayPassword">
					<text>确定</text>
				</cl-button>
			</template>
		</cl-dialog>
		<uni-popup ref="popup" type="bottom">
			<view class="offer-wrapper">
				<view class="offer-head-wrapper">
					<text>竞拍价：</text>
					<uni-number-box :value="lotInfo.lotRecordList.length <= 0 ? lotInfo.startPrice + lotInfo.markupRange : lotInfo.lotRecordList[0].price + lotInfo.markupRange"
					 class="number-box" :min="lotInfo.lotRecordList.length <= 0 ? lotInfo.startPrice + lotInfo.markupRange : lotInfo.lotRecordList[0].price + lotInfo.markupRange"
					 :max="1000000" :step="lotInfo.markupRange" @change="priceChange"></uni-number-box>
				</view>
				<view class="offer-foot-wrapper">
					<cl-button @tap="close">
						<text>取消</text>
					</cl-button>
					<cl-button type="primary" style="background-color: #2196F3;" @tap="submit">
						<text>提交</text>
					</cl-button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import uniNumberBox from "@/components/uni-number-box/uni-number-box.vue"
	export default {
		components: {
			uniPopup,
			uniNumberBox
		},
		data() {
			return {
				lotId: '',
				lotInfo: {
					lotId: '',
					type: '',
					title: '',
					info: '',
					date: '',
					endDate: '',
					startPrice: '',
					markupRange: '',
					images: ["/static/swiperImage/img1.jpg",
						"/static/swiperImage/img2.jpg",
						"/static/swiperImage/img3.jpg",
					],
					tag: 1,
					look: 0,
					collectionNum: 0,
					auctionUid: '',
					uid: '',
					name: '',
					photo: '',
					lotRecordList: [],
				},
				price: 0,
				isCollection: false,
				layout: [],
				splitor: [],
				loadNum: 0,
				dialog: false,
				payPassword: ''
			}
		},
		methods: {
			countdownChange(s) {
				if ((s.length == 3 || (s.length == 4 && s[0] == "00")) && this.layout.indexOf("day") != -1) {
					this.layout.shift();
					this.splitor.shift();
				} else if ((s.length == 2 || (s.length == 3 && s[0] == "00")) && this.layout.indexOf("hour") != -1) {
					this.layout.shift();
					this.splitor.shift();
				}
			},
			gotoRecord(lotId) {
				uni.navigateTo({
					url: "../lotRecord/lotRecord?lotId=" + lotId
				})
			},
			gotoUserInfo(uid) {
				uni.navigateTo({
					url: "../userInfo/userInfo?uid=" + uid
				})
			},
			// 出价change
			priceChange(price) {
				this.price = price;
			},
			// 提交出价
			submit() {
				this.$refs["confirm"].open({
					title: "提示",
					message: "确定出价吗？",
					callback: ({
						action
					}) => {
						if (action === "confirm") {
							this.$refs.popup.close();
							uni.request({
								method: "PUT",
								url: this.$serverUrl + "updateLotPrice",
								data: {
									lotId: this.lotInfo.lotId,
									uid: this.$common.user.uid,
									price: this.price
								},
								success: (res) => {
									if (this.checkSucess(res)) {
										// 插入拍卖纪录
										this.insertLotRecord();
									} else {
										this.$refs["message"].open({
											type: 'cancel',
											message: res.data.msg,
											duration: 2000,
											iconSize: 24
										});
									}
								}
							})
						}
					},
				});
			},
			// 插入拍卖纪录
			insertLotRecord() {
				let lotRecord = {
					date: this.getNowFormatDate(),
					price: this.price,
					uid: this.$common.user.uid,
					lotId: this.lotId
				}
				uni.request({
					method: "POST",
					url: this.$serverUrl + "insertLotRecord",
					data: lotRecord,
					success: (res) => {
						if (this.checkSucess(res)) {
							this.$refs["message"].open({
								type: 'success',
								message: "参拍成功",
								duration: 1500,
								iconSize: 24
							});
							// 提交成功，刷新页面
							setTimeout(() => {
								uni.redirectTo({
									url: "./lotDetail?lotId=" + this.lotId
								})
							}, 1500)
						} else {
							this.$refs["message"].open({
								type: 'cancel',
								message: res.data.msg,
								duration: 2000,
								iconSize: 24
							});
						}
					}
				})
			},
			// 收藏
			collect() {
				if (!this.$common.hasLogin) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "您尚未登录，请先登录",
						duration: 1500,
						iconSize: 24
					});
					setTimeout(() => {
						this.clearTimeoutAndInterval();
						uni.redirectTo({
							url: "../login/login?url=lotDetail&lotId=" + this.lotId
						})
					}, 1500)
					return
				}
				if (this.isCollection) {
					// 取消收藏
					uni.request({
						method: "DELETE",
						url: this.$serverUrl + "lotCollection",
						data: {
							uid: this.$common.user.uid,
							lotId: this.lotInfo.lotId
						},
						success: (res) => {
							if (this.checkSucess(res)) {
								this.$refs["message"].open({
									type: 'success',
									message: "取消收藏成功",
									duration: 2000,
									iconSize: 24
								});
								this.isCollection = false;
							} else {
								this.$refs["message"].open({
									type: 'cancel',
									message: res.data.msg,
									duration: 2000,
									iconSize: 24
								});
								this.isCollection = true;
							}
						}
					})
				} else {
					// 收藏
					uni.request({
						method: "POST",
						url: this.$serverUrl + "lotCollection",
						data: {
							uid: this.$common.user.uid,
							lotId: this.lotInfo.lotId
						},
						success: (res) => {
							if (this.checkSucess(res)) {
								this.$refs["message"].open({
									type: 'success',
									message: "收藏成功",
									duration: 2000,
									iconSize: 24
								});
								this.isCollection = true;
							} else {
								this.$refs["message"].open({
									type: 'cancel',
									message: res.data.msg,
									duration: 2000,
									iconSize: 24
								});
								this.isCollection = false;
							}
						}
					})
				}
			},
			// 参加拍卖
			click() {
				if (!this.$common.hasLogin) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "您尚未登录，请先登录",
						duration: 1500,
						iconSize: 24
					});
					setTimeout(() => {
						this.clearTimeoutAndInterval();
						uni.redirectTo({
							url: "../login/login?url=lotDetail&lotId=" + this.lotId
						})
					}, 1500)
					return
				}
				if (this.$common.user.uid == this.lotInfo.uid) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "您不能参与自己的拍卖",
						duration: 2000,
						iconSize: 24
					});
					return
				}
				this.openDialog();
			},
			checkPayPassword() {
				if (this.payPassword == null || !RegExp(/^[0-9]{6}$/).test(this.payPassword)) {
					this.$refs["message"].open({
						type: 'cancel',
						message: "密码为6位纯数字",
						duration: 1500,
						iconSize: 24
					});
					return;
				}
				let data = {
					uid: this.$common.user.uid,
					payPassword: this.payPassword
				}
				uni.request({
					method: "POST",
					data: data,
					url: this.$serverUrl + "/judgePayPassword",
					success: (res) => {
						console.log(res)
						if (this.checkSucess(res)) {
							this.payPassword = '';
							this.closeDialog();
							this.$refs.popup.open();
						} else {
							this.$refs["message"].open({
								type: 'cancel',
								message: res.data.msg,
								duration: 2000,
								iconSize: 24
							});
						}
					}
				})
			},
			// 网络请求是否成功的判断
			checkSucess(res) {
				let isSuccess = false;
				if (res.data.statusCode == "200") {
					if (res.data.msg == "success") {
						isSuccess = true;
					}
				}
				return isSuccess;
			},
			handleLotImages(res) {
				// 处理图片地址
				for (let j = 0; j < res.data.data.length; j++) {
					if (res.data.data[j].images != null) {
						let image = res.data.data[j].images.split("?");
						for (let i = 0; i < image.length; i++) {
							image[i] = "http://localhost:8081/image/" + res.data.data[j].lotId + "/" + image[i];
						}
						res.data.data[j].images = image;
					}
				}
			},
			// 处理头像
			handlePhoto(res) {
				let data = res.data.data;
				for (let i = 0; i < data.length; i++) {
					let photo = data[i].photo;
					if (photo == null || photo == "") {
						res.data.data[i].photo = "/static/icon/head-icon.jpg";
						continue;
					}
					res.data.data[i].photo = "http://localhost:8081/photo/" + photo;
				}
			},
			loadContent() {
				// 更新浏览量
				this.$common.request(this.$serverUrl + "lotLook/" + this.lotId, null, "GET", null, null,
					() => {
						// 进入页面加载初数据
						this.$common.request(this.$serverUrl + "lot/" + this.lotId, null, "GET", this.successCallbackByDetail);
					});
				if (this.$common.hasLogin) {
					uni.request({
						method: "GET",
						url: this.$serverUrl + "getIsCollection?uid=" + this.$common.user.uid + "&lotId=" + this.lotId,
						success: (res) => {
							if (this.checkSucess(res)) {
								this.isCollection = res.data.data[0]
							}
						}
					})
				}
			},
			successCallbackByDetail(res) {
				if (this.checkSucess(res)) {
					this.handleLotImages(res);
					this.handlePhoto(res);
					let data = res.data.data[0];
					// 将内容填入
					this.lotInfo = {
						lotId: data.lotId,
						type: data.type,
						title: data.title,
						info: data.info,
						date: data.date,
						endDate: data.endDate,
						startPrice: data.startPrice,
						markupRange: data.markupRange,
						images: data.images,
						tag: data.tag,
						look: data.look,
						collectionNum: data.collectionNum,
						auctionUid: data.auctionUid,
						uid: data.uid,
						name: data.name,
						photo: data.photo,
						lotRecordList: data.lotRecordData
					}
					if (this.loadNum == 0) {
						let datetime = new Date(this.lotInfo.endDate);
						let now = new Date();
						let time = datetime.getTime() - now.getTime();
						if (time / 1000 < 60 * 60 && this.layout.length == 0) {
							this.layout.push('minute');
							this.layout.push('second');
							this.splitor.push('分');
							this.splitor.push('秒');
						} else if (time / 1000 < 60 * 60 * 24 && this.layout.length == 0) {
							this.layout.push('hour');
							this.layout.push('minute');
							this.layout.push('second');
							this.splitor.push('时');
							this.splitor.push('分');
							this.splitor.push('秒');
						} else {
							this.layout.push('day');
							this.layout.push('hour');
							this.layout.push('minute');
							this.layout.push('second');
							this.splitor.push('天');
							this.splitor.push('时');
							this.splitor.push('分');
							this.splitor.push('秒');
						}
						if (time > 0 && this.$common.timeoutID == null && this.$common.intervalID == null) {
							// 结束拍卖之后刷新
							this.$common.timeoutID = setTimeout(() => {
								this.$common.request(this.$serverUrl + "lot/" + this.lotId, null, "GET", this.successCallbackByDetail);
								this.loadNum = this.loadNum + 1;
							}, time + 1000)
							this.$common.intervalID = setInterval(() => {
								this.$common.request(this.$serverUrl + "lot/" + this.lotId, null, "GET", this.successCallbackByDetail);
								this.loadNum = this.loadNum + 1;
							}, 1000)
						}
					}
				}
				uni.stopPullDownRefresh();
			},
			openDialog() {
				this.dialog = true;
			},
			closeDialog() {
				this.dialog = false;
			},
			close() {
				this.$refs.popup.close();
			},
			int2str(num) {
				let numberStr = num.toString()
				let str = numberStr.split('').reverse()
				for (let i = 0; i < str.length; i++) {
					if ((i + 1) % 4 === 0) {
						str.splice(i, 0, ',')
					}
				}
				str.reverse()
				let handleResult = ''
				for (let j = 0; j < str.length; j++) {
					handleResult += str[j]
				}
				return handleResult
			},
			getCNDate(FormatDate) {
				let date = new Date(FormatDate);
				let now = new Date();
				let year = date.getFullYear();
				let mouth = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				if (date.getFullYear() < now.getFullYear()) {
					return year + "年" + mouth + "月" + day + "日 " + hour + ":" + min;
				} else {
					return mouth + "月" + day + "日 " + hour + ":" + min;
				}
			},
			formatRecordTime(date) {
				let time = new Date(date.replace(/-/g, "/"));
				let now = new Date();
				let mouth = time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1;
				let day = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
				let hour = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
				let min = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
				let sec = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
				if (time.getFullYear() < now.getFullYear()) {
					return year + "." + mouth + "." + day + " " + hour + ":" + min + ":" + sec;
				} else {
					return mouth + "." + day + " " + hour + ":" + min + ":" + sec;
				}
				return time;
			},
			getCNType(type) {
				let text = "";
				switch (type) {
					case 1:
						text = "手机";
						break;
					case 2:
						text = "电脑";
						break;
					case 3:
						text = "数码";
						break;
					case 4:
						text = "图书";
						break;
					case 5:
						text = "其他";
						break;
				}
				return text;
			},
			getNowFormatDate() {
				var date = new Date();
				var seperator1 = "-";
				var seperator2 = ":";
				var year = date.getFullYear();
				var month = date.getMonth() + 1;
				var strDate = date.getDate();
				var hour = date.getHours();
				var min = date.getMinutes();
				var sec = date.getSeconds();
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (strDate >= 0 && strDate <= 9) {
					strDate = "0" + strDate;
				}
				var currentdate = year + seperator1 + month + seperator1 + strDate + " " + hour + seperator2 + min + seperator2 +
					sec;
				return currentdate;
			},
			clearTimeoutAndInterval() {
				if (this.$common.timeoutID != null) {
					clearTimeout(this.$common.timeoutID);
					this.$common.timeoutID = null;
				}
				if (this.$common.intervalID != null) {
					clearInterval(this.$common.intervalID);
					this.$common.intervalID = null;
				}
			}
		},
		onLoad(option) {
			this.lotId = option.lotId;
			this.loadContent();
		},
		onPullDownRefresh() {
			setTimeout(() => {
				this.$common.request(this.$serverUrl + "lot/" + this.lotId, null, "GET", this.successCallbackByDetail);
				this.loadNum = this.loadNum + 1;
			}, 500)
		},
		onBackPress() {
			this.clearTimeoutAndInterval();
		}
	}
</script>

<style lang="scss">
	@import url("lotDetail.css");

	/deep/.cl-countdown__number {
		font-size: 14px;
		background-color: $uni-color-primary;
		color: #FFFFFF;
		min-width: 0;
		margin: 0;
		padding: 0;
		padding-left: 10rpx;
	}

	/deep/ .cl-message {
		&__content {
			font-size: 15px;
		}
	}
</style>
